﻿@using Mapster;
@using OnWork.DataCenter.BLL.Standard;
<ValidateForm Model="@jsonToDataTableConfig" 
              OnValidSubmit="@OnValidSubmit">

    <div class="row">
        <div class="col-sm-3">
            <Select @bind-Value="@jsonToDataTableConfig.Type" ShowLabel="true" DisplayText="解析类型" OnSelectedItemChanged="@OnSelectedItemChanged">
            </Select>


            <BootstrapInput PlaceHolder="请输入JSONPATH表达式" IsDisabled="defaultDisabled"
                            TValue="string"
                            IsSelectAllTextOnEnter="true"
                            ShowLabel="true"
                            DisplayText="主数据源" @bind-Value="@jsonToDataTableConfig.dataSelectToken" />
        </div>
        <div class="col-sm-9"  >
            <Table TItem="DataTableCol" UseInjectDataService="false" IsPagination="false" DoubleClickToEdit="true" 
                   IsStriped="true" IsBordered="true" ShowSkeleton="true" IsMultipleSelect="true" ShowEmpty="false" ShowLoading="true" ShowColumnList="true"
                   ShowToolbar="true" ShowExtendButtons="true"
                   ShowSearch="true" ShowAdvancedSearch="false"
                   AutoGenerateColumns="false" EditMode="EditMode.InCell"
                   OnSaveAsync="@OnSaveAsync" OnDeleteAsync="@OnDeleteAsync"
                   ShowToastAfterSaveOrDeleteModel="false" Items="@jsonToDataTableConfig.Cols">

                <TableColumns>
                    <TableColumn Text="字段名" @bind-Field="@context.ColName" Width="180" />
                    <TableColumn Text="类型" @bind-Field="@context.ColType" Width="100" />
                    <TableColumn Text="查询条件" @bind-Field="@context.ColSelectToken" />
                    <TableColumn Text="说明" @bind-Field="@context.Remark" />
                </TableColumns>

                <RowButtonTemplate>
                    @*<TableCellButton Color="Color.Info" Icon="fa-solid fa-pen" Text="测试连接" OnClick="@(()=>OnConnTestAsync(context))" IsAsync="true" />*@
                    @*<TableCellPopconfirmButton Color="Color.Info" Icon="fa-solid fa-pen" Text="测试" />*@
                </RowButtonTemplate>
                @*<TableColumns>
                <TableColumn @bind-Field="@context.Hobby" Items="GetHobbys(context)" />
                </TableColumns>*@
            </Table>
        </div>
    </div>
    <div class="form-footer mt-3">
        <DialogCloseButton />
        <Button Color="Color.Primary" ButtonType="ButtonType.Submit" Icon="fa-solid fa-floppy-disk" Text="保存" />
    </div>
</ValidateForm>

    

@code {
    /// <summary>
    /// Json转DataTable配置
    /// </summary>
    private OnWork.DataCenter.BLL.Standard.JsonToDataTableConfig jsonToDataTableConfig = new BLL.Standard.JsonToDataTableConfig() { Cols = new List<BLL.Standard.DataTableCol>() };

    [Parameter]
    public Action? OnClose { get; set; }

    [Parameter]
    public Action<JsonToDataTableConfig>? OnSave { get; set; }


    [CascadingParameter(Name = "BodyContext")]
    private object? Context { get; set; }

    [CascadingParameter]
    private Modal? Dialog { get; set; }

    protected override void OnParametersSet()
    {
        base.OnParametersSet();

        if (Context is OnWork.DataCenter.BLL.Standard.JsonToDataTableConfig)
        {
            jsonToDataTableConfig = Context as OnWork.DataCenter.BLL.Standard.JsonToDataTableConfig;
        }

    }

    /// <summary>
    /// 默认类型是否可用
    /// </summary>
    private bool defaultDisabled = false;

    /// <summary>
    /// 当选项修改时
    /// </summary>
    /// <param name="item"></param>
    /// <returns></returns>
    private async Task OnSelectedItemChanged(SelectedItem item)
    {
        var val = item.Value;

        if (Enum.TryParse(item.Value, true, out JsonToDataTableType result))
        {
            if (result==JsonToDataTableType.Default)
            {
                defaultDisabled = false;
            }else
            {
                defaultDisabled = true;
            }

        }

        //JsonToDataTableType.p

        await Task.CompletedTask;
    }

    ///// <summary>
    ///// 分页查询
    ///// </summary>
    ///// <param name="options"></param>
    ///// <returns></returns>
    //private async Task<QueryData<JsonToDataTableCol>> QueryAsync(QueryPageOptions options)
    //{
    //    QueryData<JsonToDataTableCol> result = new QueryData<JsonToDataTableCol>();

    //    return jsonToDataTableConfig.Cols;

    //}

    /// <summary>
    /// 删除数据
    /// </summary>
    /// <param name="items"></param>
    /// <returns></returns>
    private async Task<bool> OnDeleteAsync(IEnumerable<DataTableCol> items)
    {

        jsonToDataTableConfig.Cols.RemoveAll(x=>items.Contains(x));

        return await Task.FromResult(true);
        //var result = await dBConnBLL.DeleteDataAsync(item.Select(x => x.ID).ToArray());

        //return await ShowSqlReturnMsg(result);
    }

    /// <summary>
    /// 保存数据
    /// </summary>
    /// <param name="item"></param>
    /// <param name="changedType"></param>
    /// <returns></returns>
    private async Task<bool> OnSaveAsync(DataTableCol item, ItemChangedType changedType)
    {
        //RESTfulResult<object> result;
        if (changedType == ItemChangedType.Update) // 更新
        {
            var entry = jsonToDataTableConfig.Cols.Where(x=>x.id==item.id).FirstOrDefault();

            item.Adapt(entry);
            ////var result = await dBConnBLL.UpdateDataAsync(item.Adapt<OnWork.DataCenter.DAL.DataCenter.DataStandard>());
            //return await ShowSqlReturnMsg(result);

            return await Task.FromResult(true);
        }
        else //新增
        {
            jsonToDataTableConfig.Cols.Add(item);
            return await Task.FromResult(true);
            //var result = await dBConnBLL.AddDataAsync(item.Adapt<OnWork.DataCenter.DAL.DataCenter.DataStandard>());
            //return await ShowSqlReturnMsg(result);
        }
    }


    private async Task OnValidSubmit(EditContext item)
    {
        // do someting like save model into db

        OnSave(jsonToDataTableConfig);

        // 关闭弹窗
        // close Dialog
        await Dialog.Close();

        // 显示 Toast 提示弹窗
        //await Toast.Show(new ToastOption() { Title = "保存数据", Content = "保存成功，4 秒后自动关闭" });
    }
}
